package com.ssb.service.pay;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.apache.api.vo.ResultEntity;
import com.apache.cache.util.Validator;
import com.apache.exception.BusinessException;
import com.apache.ius.common.CommonUtils;
import com.apache.ius.plugin.IusPluginUtil;
import com.apache.tools.DataMap;
import com.apache.tools.StrUtil;
import com.ssb.util.AESUtil;
import com.ssb.util.SendHttpUtil;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Map;

@Service
public class AppPayService {
    private Logger log = Logger.getLogger(getClass());

    public JSONObject  appPay(String exchangeNo,String infoId){

        //设置日期输出的格式
        SimpleDateFormat dateFormat=new SimpleDateFormat("yyyyMMddHHmmss");
        BigDecimal totalMoney =new BigDecimal("0");
        //固定配置
        String enterprise_num = CommonUtils.getConfigVal("app_enterprice_num");//保融分配的代表某个企业的编号
        String command_code = CommonUtils.getConfigVal("app_command_code");//指令类型
        String br_wx_pay_app_progran_url = CommonUtils.getConfigVal("br_wx_pay_app_progran_url");//请求url
        String app_call_back_url = CommonUtils.getConfigVal("app_call_back_url");//前端跳转路径
        String notify_url= CommonUtils.getConfigVal("br_wx_notify_url");//通知地址

        //准备数据
        String body = "";
        String applicantName = "";
        String applicantCertiNo = "";
        String requestNo = "";
        try {
            Map<String,Object> whereMap = new HashMap<>();
            whereMap.put("ssInsurOrder.w_infoId",infoId);
            whereMap.put("ssInsurPro.infoId","[ssInsurOrder.proId]");
            whereMap.put("result_column","ssInsurOrder.tradeNo,ssInsurOrder.premium,ssInsurPro.riskCname,ssInsurOrder.applicantName,ssInsurOrder.applicantCertiNo,ssInsurOrder.requestNo");
            ResultEntity resultEntity = IusPluginUtil.getInstance().select("ssb","obj", "s_ssInsurOrder,s_ssInsurPro", whereMap);
            DataMap dataMap = (DataMap)resultEntity.getEntity();
            if(!Validator.isEmpty(dataMap)){
                HashMap<String,Object> ssInsurOrderMap = (HashMap<String,Object>)dataMap.get("ssInsurOrder");
                HashMap<String,Object> ssInsurProMap = (HashMap<String,Object>)dataMap.get("ssInsurPro");
                if(exchangeNo.equals(String.valueOf(ssInsurOrderMap.get("tradeNo")))){
                    BigDecimal hundred = new BigDecimal("100");
                    totalMoney = new BigDecimal(String.valueOf(ssInsurOrderMap.get("premium")));
                    totalMoney = totalMoney.multiply(hundred);
                    body = String.valueOf(ssInsurProMap.get("riskCname"));//订单内容body
                    applicantName = String.valueOf(ssInsurOrderMap.get("applicantName"));//投保人名称
                    applicantCertiNo = String.valueOf(ssInsurOrderMap.get("applicantCertiNo"));//投保人证件号码
                    requestNo = String.valueOf(ssInsurOrderMap.get("requestNo"));//交易流水号
                }else {
                    new BusinessException("该订单号与支付流水号不匹配，请联系客服核实。");
                }
            }else {
                new BusinessException("该订单号下不存在订单，请联系客服核实。");
            }
            //订单金额
            String total_fee=String.valueOf(totalMoney.intValue());//单位是分

            log.info("-----保融通知接口----statr");
            Map data = new HashMap();
            JSONObject head = new JSONObject();
            head.put("EnterpriseNum", enterprise_num);
            head.put("CommandCode", command_code);
            head.put("TransSeqID", System.currentTimeMillis());
            data.put("Head",head);

            JSONObject transRequest = new JSONObject();
            transRequest.put("ReqNo", requestNo);//交易流水号
            transRequest.put("CertiNo", requestNo);//投保单号
            transRequest.put("ExchangeNo", exchangeNo);//支付流水号
            transRequest.put("CustName", StrUtil.doNull(applicantName,"0"));//姓名，没有可填0
            transRequest.put("CertNum", StrUtil.doNull(applicantCertiNo,"0"));//证件号，没有可填0
            transRequest.put("Amount", total_fee);//缴费总金额（元，精确到小数两位）。如果不调用见费系统的话这个字段是必填的，否则非必填。
            transRequest.put("DiscountAmount", "0.00");//优惠金额（元，精确到小数两位）
            transRequest.put("ComCode", "1000");//机构代码
            transRequest.put("CallFlag", "2");//外部系统调用类型枚举（0 不调用；1 见费系统）默认0不调用 2 查询缴费单的操作
            transRequest.put("Channel", "W210-Q"); //显示的付款渠道
            transRequest.put("IsCheckIdentity", "0"); //是否校验支付身份信息标记，会结合证件类型、证件号、姓名去做身份校验，1：校验（普通实名），2：校验（江苏平台实名）3：校验（保信平台实名），4：校验（深圳平台实名），0：不校验，默认0
            transRequest.put("Memo", body);//商品描述
            transRequest.put("CallBackUrl",app_call_back_url); //前端跳转地址，不传则需要提供默认地址给保融，在保融后端配置
            transRequest.put("NoticeUrl", notify_url);//后台通知地址，不传则需要提供默认地址给保融，在保融后端配置
            transRequest.put("ReSendUrl", "");//重新发起请求地址，不传则需要提供默认地址给保融，在保融后端配置
            data.put("TransRequest",transRequest);

            final String aesKey= "ABQDKEY";
            log.info("APP调起收银台支付请求参数params----->>>>>>"+data.toString());
            log.info("APP调起收银台支付请求参数url----->>>>>>"+br_wx_pay_app_progran_url);

            String resp = String.valueOf(sendAppPayInterface(br_wx_pay_app_progran_url, data,null,aesKey));
            JSONObject jsonObj = JSON.parseObject(resp);
            log.info("返回参数===="+jsonObj);
            log.info("-----保融通知接口----end");
            return jsonObj;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * app支付发送接口请求
     * @param map
     * @return
     */
    protected String sendAppPayInterface(String url,Map<String, Object> map,Map<String,String> heads,String aesKey){
        log.info("请求路径===="+url);
        String result = SendHttpUtil.sendHttpStr(url,"post", map, heads, aesKey);
        if(Validator.isNotNull(result)){
            String str = AESUtil.decrypt(result,aesKey);
            return str;
        }
        return null;
    }

}
